
import { CreateDeploymentUnitDto } from './dto/create-deployment-unit.dto';
import { UpdateDeploymentUnitDto } from './dto/update-deployment-unit.dto';
import { ResponseUtil } from '../common/utils/response.util';
import { WebsocketGateway } from '../websocket/websocket.gateway';
import { forwardRef, Inject,Injectable  } from '@nestjs/common';
import { LogService } from '../log/log.service';
@Injectable()
export class DeploymentUnitService {

  constructor(
    @Inject(forwardRef(() => WebsocketGateway)) private websocketGateway: WebsocketGateway,
    @Inject(forwardRef(() => LogService)) private logService: LogService
  ) {}

  //列表数据
  private records = Array.from({ length: 50 }, (_, i) => ({
    id: i + 1,
    createdBy: `user${i + 1}`,
    createdTime: Date.now() + i * 1000,
    updatedBy: `user${i + 1}`,
    updatedTime: Date.now() + i * 1000,
    deploymentId: i+1, // 生成 40-49 之间的 deploymentId
    commitId: `commit${i + 1}`,
    commitMessage: `commitMessage${i + 1}`,
    deploymentName: `deploymentName${i + 1}`,
    minioAddress: `minioAddress${i + 1}`,
    versionNumber: i,
    startDate: Date.now() + i * 1000,
    endTime: Date.now() + i * 1000,
    startScript: `startupScript${i}`, //启动脚本
  }));


  // 部署数量对象
  private deployCount = {
    totalNum:239,
    deployNum:123,
    ndNum:116,
  }


  // 分页查询
  pageList(body: any) {
    const { deploymentName,startTime,endTime } = body
    const { currentPage, pageSize } = body;
    const start = (currentPage - 1) * pageSize;
    const end = start + pageSize;
    const records = this.records.filter(item=>{
      const matchDeploymentName = !deploymentName || item.deploymentName==deploymentName;
      const matchStartDate = !startTime || item.startDate >= startTime;
      const matchEndTime = !endTime || item.endTime <= endTime;
      return matchDeploymentName && matchStartDate && matchEndTime;
    }).slice(start, end);
    const data = {
      records,
      total: this.records.length,
    }
    return ResponseUtil.success(data, '查询成功');
  }

  // 条件查询
  /**
   * 使用了"短路逻辑"进行条件判断：
   * 对每个查询条件，首先检查参数是否存在
   * 如果参数不存在（为空、null或undefined），则该条件自动返回true（不进行过滤）
   * 如果参数存在，则应用相应的过滤条件
   * 改用了"与"（&&）逻辑来组合所有条件，这意味着：
   * 所有有效的查询条件必须同时满足
   * 未提供的参数不会影响查询结果
   */
  queryList(body: any) {
    const { deploymentName, startDate, endTime, deploymentId } = body
    const records = this.records.filter(item => {
      // 只有当参数有值时才进行过滤
      const matchDeploymentName = !deploymentName || item.deploymentName.includes(deploymentName);
      const matchStartDate = !startDate || item.startDate >= startDate;
      const matchEndTime = !endTime || item.endTime <= endTime;
      // 特别处理 deploymentId，确保类型一致
      const matchDeploymentId = deploymentId === undefined || deploymentId === null || 
                               Number(item.deploymentId) === Number(deploymentId);
      // 所有传入的条件都必须满足（与逻辑）
      return matchDeploymentName && matchStartDate && matchEndTime && matchDeploymentId;
    });
    const data = records
    return ResponseUtil.success(data, '查询成功');
  }

  issueStop(body:any){
    return ResponseUtil.success(body, '停止成功');
  }

  // 停止运行部署物日志
  issueStopLog(body: any) {
    this.logService.stopPushingLogUpdates();
    return ResponseUtil.success(body, '停止成功');
  }

  // 一键部署
  issueDownload(body: any) {
    return ResponseUtil.success(body, '一键部署成功');
  }

  // 删除部署物相关节点
  delete(body: any) {
    return ResponseUtil.success(body, '一键部署成功');
  }

  // 删除部署物文件
  deleteList(body: any) {
    body.ids.forEach(id=> {
      this.records = this.records.filter(item => item.deploymentId !== id);
    });
    return ResponseUtil.success(body, '删除成功');
  }


  // 获取所有部署数量
  getAllDeploymentCount() {
    return ResponseUtil.success(this.deployCount, '获取所有部署数量成功');
  }
}
